package com.itheima.listener;

import cn.idev.excel.context.AnalysisContext;
import cn.idev.excel.read.listener.ReadListener;
import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.OrderSetting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @className OrderSettingDataListener
 */
public class OrderSettingDataListener implements ReadListener<OrderSetting> {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderSettingDataListener.class);
    private static final int BATCH_COUNT = 100;
    private final OrderSettingMapper mapper;
    private List<OrderSetting> cachedDataList;

    public OrderSettingDataListener(OrderSettingMapper mapper) {
        this.mapper = mapper;
        this.cachedDataList = new ArrayList<>(BATCH_COUNT);
    }

    @Override
    public void invoke(OrderSetting orderSetting, AnalysisContext analysisContext) {
        // 检查缓存数据列表是否为空，如果为空则初始化
        if (cachedDataList == null) {
            cachedDataList = new ArrayList<>(BATCH_COUNT);
        }
        // 将订单设置对象添加到缓存数据列表中
        cachedDataList.add(orderSetting);
        // 当缓存数据列表达到预设的批量处理数量时，执行批量保存操作
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveBatch();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (cachedDataList != null && !cachedDataList.isEmpty()) {
            saveBatch();
        }
    }

    private void saveBatch() {
        LOGGER.info("开始批量插入 {} 条数据", cachedDataList.size());
        try {
            // 批量插入数据库
            mapper.batchInsert(cachedDataList);
            LOGGER.info("批量插入成功");
        } catch (Exception e) {
            LOGGER.error("批量插入失败", e);
            throw new RuntimeException("批量插入失败", e);
        } finally {
            // 清空缓存数据列表
            cachedDataList.clear();
        }
    }

}
